package net

import (
	"data-system/excel"
	"log"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

type Heartbeat struct {
	Id        string
	conn      *websocket.Conn
	closeChan chan struct{}
	wg        *sync.WaitGroup
}

func NewHeartbeat(id string, conn *websocket.Conn, wg *sync.WaitGroup) *Heartbeat {
	return &Heartbeat{
		Id:        id,
		conn:      conn,
		closeChan: make(chan struct{}),
		wg:        wg,
	}
}

func (h *Heartbeat) Watch() {
	defer h.wg.Done()
	ticker := time.NewTicker(3 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			if err := h.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
				excel.UnRegister(h.Id)
				log.Println("心跳失败:", err)
				close(h.closeChan)
				return
			}
		case <-h.closeChan:
			return
		}
	}
}
